package com.lagou.springsessiontest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

/**
 * @author zhangxuyuan
 * @version 1.0
 * @date 2020/11/14
 */
@Controller
public class IndexController {

    @Autowired
    UserRepository userRepository;

    @Value("${server.port}")
    String port;

    @GetMapping("/")
    public String index(HttpSession session, Model model)
    {
        if(session.getAttribute("user")==null)
        {return "redirect:/login";}
        model.addAttribute("id",session.getId());
        model.addAttribute("username",((User)session.getAttribute("user")).getName());
        model.addAttribute("port",port);
        return "index";
    }

    @GetMapping("/login")
    public String loginpage()
    {
        return "login";
    }

    @PostMapping("/login")
    public String login(@RequestParam("name")String name,@RequestParam("password") String password,
        HttpSession session,Model model)
    {
        User user = userRepository.findByNameAndPassword(name, password);
        if(user==null)
        {
            return "login";
        }
        session.setAttribute("user",user);
        return "redirect:/";
    }
}
